package com.zheng.umbrella.web.controller.manage;

import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.util.PayCommonUtil;
import com.zheng.common.util.QRCodeUtil;
import com.zheng.common.util.ZipUtil;
import com.zheng.umbrella.common.constant.UmbrellaConstant;
import com.zheng.umbrella.common.constant.UmbrellaResult;
import com.zheng.umbrella.common.constant.UmbrellaResultConstant;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareApiService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareMachineService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwarePathService;
import com.zheng.umbrella.rpc.api.UmbrellaRuleDepositService;
import com.zheng.upms.dao.model.UpmsAgent;
import com.zheng.upms.dao.model.UpmsAgentExample;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.rpc.api.UpmsAgentService;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsDictService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;


/**
 * Created by Administrator on 2018/9/16.
 */
@Controller
@Api(value = "伞机管理", description = "伞机管理")
@RequestMapping("/manage/machine")
public class UmbrellaHardwareMachineController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UmbrellaHardwareMachineController.class);

    @Autowired
    private UmbrellaHardwareMachineService umbrellaHardwareMachineService;

    @Autowired
    private UmbrellaHardwarePathService umbrellaHardwarePathService;

    @Autowired
    private UpmsApiService upmsApiService;

    @Autowired
    private UmbrellaHardwareApiService umbrellaHardwareApiService;

    @Autowired
    private UmbrellaRuleDepositService umbrellaRuleDepositService;

    @Autowired
    UpmsSystemParamService upmsSystemParamService;

    @Autowired
    UpmsDictService upmsDictService;
    @Autowired
    UpmsAgentService upmsAgentService;

    @Value("${api.apicenter.baseUrl}")
    private String baseUrl;
    @Value("${api.apicenter.rebootUmbrellaMachineUrl}")
    private String rebootUmbrellaMachineUrl;


    @ApiOperation(value = "伞机首页")
    @RequiresPermissions("umbrella:machine:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/machine/index.jsp";
    }

    @ApiOperation(value = "伞机列表")
    @RequiresPermissions("umbrella:machine:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order,
            @RequestParam(required = false, value = "machineCode") String machineCode,
            @RequestParam(required = false, value = "status") Integer status) {
        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
        UmbrellaHardwareMachineExample umbrellaHardwareMachineExample = new UmbrellaHardwareMachineExample();
        UmbrellaHardwareMachineExample.Criteria criteria = umbrellaHardwareMachineExample.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        if(agentId != null){
            criteria.andAgentIdEqualTo(agentId);
        }
        if (StringUtils.isNotBlank(machineCode)) {
            criteria.andCodeEqualTo(machineCode);
        }
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            umbrellaHardwareMachineExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andCodeLike("%" + search + "%");
//            String searchVal = "%" + search + "%";
//            criteria.getCriteria().add(new UmbrellaHardwareMachineExample.Criterion(
//                    "(name like "+searchVal+" or code like "+searchVal+")"
//            ));
        }
        List<UmbrellaHardwareMachine> rows = umbrellaHardwareMachineService.selectByExampleForOffsetPage(umbrellaHardwareMachineExample, offset, limit);
        long total = umbrellaHardwareMachineService.countByExample(umbrellaHardwareMachineExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增伞机")
    @RequiresPermissions("umbrella:machine:create")
    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(ModelMap modelMap) {
        //伞机状态
        List<UpmsDict> statusList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_MACHINE_STATUS);
        modelMap.put("statusList", statusList);

        String loginUserName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        long nowtime = new Date().getTime();
        //预付金规则
        UmbrellaRuleDepositExample depositExample = new UmbrellaRuleDepositExample();
        depositExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId)
                .andStatusEqualTo(UmbrellaConstant.STATUS_UNLOCK)
                .andBeginTimeLessThanOrEqualTo(nowtime)
                .andEndTimeGreaterThanOrEqualTo(nowtime);
        List<UmbrellaRuleDeposit> depositList = umbrellaRuleDepositService.selectByExample(depositExample);
        modelMap.put("depositList", depositList);

        //租金规则
        UmbrellaRuleRentExample ruleRentExample = new UmbrellaRuleRentExample();
        ruleRentExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId)
                .andStatusEqualTo(UmbrellaConstant.STATUS_UNLOCK);
        List<UmbrellaRuleRent> ruleRentList = umbrellaHardwareApiService.selectRuleRentByExample(ruleRentExample);
        modelMap.put("ruleRentList", ruleRentList);
        //伞机型号
        List<UpmsDict> machineTypeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_MACHINE_TYPE);
        modelMap.put("machineTypeList", machineTypeList);
        return "/manage/machine/create.jsp";
    }

    @ApiOperation(value = "新增伞机")
    @RequiresPermissions("umbrella:machine:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public Object create(UmbrellaHardwareMachine umbrellaHardwareMachine) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 120, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
        long time = System.currentTimeMillis();
        umbrellaHardwareMachine.setAgentId(agentId);
        umbrellaHardwareMachine.setCtime(time);
//        umbrellaHardwareMachine.setStatus(UmbrellaConstant.UM_MACHINE_STATUS_4); //、默认未启用状态
        umbrellaHardwareMachine.setCuser(userName);
        //转小写
        if(umbrellaHardwareMachine.getCode()!=null) {
            umbrellaHardwareMachine.setCode(umbrellaHardwareMachine.getCode().toLowerCase());
        }
        int count = umbrellaHardwareMachineService.insertSelective(umbrellaHardwareMachine);
        //同步增加伞道
        if(count>0){
            for(int i=0;i<umbrellaHardwareMachine.getPathcount();i++){
                UmbrellaHardwarePath umbrellaHardwarePath = new UmbrellaHardwarePath();
                int pathNumber = i + 1;
                umbrellaHardwarePath.setCode(umbrellaHardwareMachine.getCode()+ "00" + pathNumber);
                umbrellaHardwarePath.setNumber(pathNumber);
                umbrellaHardwarePath.setName(umbrellaHardwareMachine.getCode()+ "00" + pathNumber);
                umbrellaHardwarePath.setMachineCode(umbrellaHardwareMachine.getCode());
                umbrellaHardwarePath.setAgentId(agentId);
                umbrellaHardwarePath.setStatus(Constant.CONST_ENABLE);
                umbrellaHardwarePath.setFlag(Constant.CONST_FLAG_NORMAL);
                umbrellaHardwarePath.setRemainder(0);
                umbrellaHardwarePath.setCapacity(umbrellaHardwareMachine.getPathcount()==1?umbrellaHardwareMachine.getCapacity():0);
                umbrellaHardwarePath.setCuser(userName);
                umbrellaHardwarePath.setCtime(time);
                umbrellaHardwarePathService.insert(umbrellaHardwarePath);
            }
        }
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除伞机")
    @RequiresPermissions("umbrella:machine:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {

        String[] idArray = ids.split("-");
        ArrayList<Integer> idList = new ArrayList<Integer>();
        for(int i=0;i<idArray.length;i++){
            idList.add(Integer.parseInt(idArray[i]));
        }
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andIdIn(idList);
        List<UmbrellaHardwareMachine> machineList = umbrellaHardwareMachineService.selectByExample(machineExample);

//        int count = umbrellaHardwareMachineService.deleteByPrimaryKeys(ids);
        int count = umbrellaHardwareMachineService.deleteLogicByPrimaryKeys(ids,UmbrellaHardwareMachine.class,null);
        //同步删除伞道
        if(count>0){
            if(machineList!=null && machineList.size()>0){
                ArrayList<String> codeList = new ArrayList<String>();
                for(int i=0;i<machineList.size();i++){
                    codeList.add(machineList.get(i).getCode());
                }
                UmbrellaHardwarePathExample pathExample = new UmbrellaHardwarePathExample();
                pathExample.createCriteria().andMachineCodeIn(codeList);
                UmbrellaHardwarePath path = new UmbrellaHardwarePath();
                path.setFlag(Constant.CONST_FLAG_INVALID);
//                umbrellaHardwarePathService.deleteByExample(pathExample);
                umbrellaHardwarePathService.updateByExample(path,pathExample);
            }
        }
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改伞机")
    @RequiresPermissions("umbrella:machine:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        //伞机状态
        List<UpmsDict> statusList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_UMBRELLA_MACHINE_STATUS);
        modelMap.put("statusList", statusList);
        String loginUserName = getLoginUserName();
        int agentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);
        //租金规则
        UmbrellaRuleRentExample ruleRentExample = new UmbrellaRuleRentExample();
        ruleRentExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId)
                .andStatusEqualTo(UmbrellaConstant.STATUS_UNLOCK);
        List<UmbrellaRuleRent> ruleRentList = umbrellaHardwareApiService.selectRuleRentByExample(ruleRentExample);
        modelMap.put("ruleRentList", ruleRentList);
        //伞机型号
        List<UpmsDict> machineTypeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_MACHINE_TYPE);
        modelMap.put("machineTypeList", machineTypeList);
        //获取预付金规则
        long nowtime = new Date().getTime();
        UmbrellaRuleDepositExample depositExample = new UmbrellaRuleDepositExample();
        depositExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(agentId)
                .andStatusEqualTo(UmbrellaConstant.STATUS_UNLOCK)
                .andBeginTimeLessThanOrEqualTo(nowtime)
                .andEndTimeGreaterThanOrEqualTo(nowtime);
        List<UmbrellaRuleDeposit> depositList = umbrellaRuleDepositService.selectByExample(depositExample);
        modelMap.put("depositList", depositList);

        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectByPrimaryKey(id);
        modelMap.put("umbrellaHardwareMachine", umbrellaHardwareMachine);
        return "/manage/machine/update.jsp";
    }

    @ApiOperation(value = "修改伞机")
    @RequiresPermissions("umbrella:machine:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") Integer id, UmbrellaHardwareMachine umbrellaHardwareMachine) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 20, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        //转小写
        if(umbrellaHardwareMachine.getCode()!=null) {
            umbrellaHardwareMachine.setCode(umbrellaHardwareMachine.getCode().toLowerCase());
        }
        umbrellaHardwareMachine.setId(id);
        int count = umbrellaHardwareMachineService.updateByPrimaryKeySelective(umbrellaHardwareMachine);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }
    @ApiOperation(value = "重启伞机")
    @RequiresPermissions("umbrella:machine:reboot")
    @RequestMapping(value = "/reboot/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object reboot(@PathVariable("ids") String ids) {
        if(StringUtils.isBlank(ids)){
            return new UmbrellaResult(UmbrellaResultConstant.FAILED, "未选择伞机");
        }
        String[] idArr = ids.split(",");
        ArrayList<Integer> idList = new ArrayList<Integer>();
        for(int i=0;i<idArr.length;i++){
            idList.add(Integer.parseInt(idArr[i]));
        }
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andIdIn(idList);
        List<UmbrellaHardwareMachine> machineList = umbrellaHardwareMachineService.selectByExample(machineExample);

        if(machineList==null || machineList.isEmpty()){
            return new UmbrellaResult(UmbrellaResultConstant.FAILED, "未选择伞机");
        }
        String[] codes =new String[machineList.size()];
        for(int i=0;i<machineList.size();i++){
            codes[i] = machineList.get(i).getCode();
        }

        String url = baseUrl + rebootUmbrellaMachineUrl + "?codes=" + StringUtils.join(codes,","); ;
        String result = PayCommonUtil.call4Post(url);
        if ("SUCCESS".equals(result)) {
            return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, "重启伞机提交完成");
        }else{
            return new UmbrellaResult(UmbrellaResultConstant.FAILED,"重启伞机提交异常");
        }
    }
    /**
     * 查看伞机二维码
     * @param id
     * @param request
     * @param response
     * @throws Exception
     */
    @ApiOperation(value = "查看伞机二维码")
    @RequiresPermissions("umbrella:machine:getqrcode")
    @RequestMapping(value = "/getQRCode/{id}",method = {RequestMethod.GET, RequestMethod.POST})
    public void getQRCode(@PathVariable("id") Integer id, HttpServletRequest request,  HttpServletResponse response) throws Exception {
        //查询伞机
        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectByPrimaryKey(id);
        UpmsAgent upmsAgent = upmsAgentService.selectByPrimaryKey(umbrellaHardwareMachine.getAgentId());
        //判断文件夹是否存在
        String realPath = request.getSession().getServletContext().getRealPath("");
        String resourcesPath = (realPath.endsWith(File.separator)?realPath:realPath+File.separator) + "resources";
        String qrcodePath =  resourcesPath+ File.separator + "qrcode";
        File filedir = new File(qrcodePath);
        if (!filedir.exists()) {
            filedir.mkdir();
        }
        String qrcodeImg = qrcodePath + File.separator + umbrellaHardwareMachine.getCode() + "." + QRCodeUtil.FORMAT_NAME;
        String logoImgFile = resourcesPath + File.separator + UmbrellaConstant.QRCODE_LOGO_IMAGE_NAME;
        String  machineQRCodeWechatappPrefix= upmsSystemParamService.querySystemParamValueByParam_key("QRCODE_MACHINE_WECHATAPP_PREFIX_PROD");
        File imageFile = new File(qrcodeImg);
        //判断文件是否存在，则生成
        if (!imageFile.exists()) {
            // 拿到图片流
            // 拿到图片流https://www.bjs-tech.cn/api/mqrcode/prod/dev0001
            String qrcode = machineQRCodeWechatappPrefix + UmbrellaConstant.QRCODE_MACHINE_WECHATAPP_PREFIX_PROD + umbrellaHardwareMachine.getCode();
            //判断对应代理是否使用独立小程序
            if(upmsAgent!=null && upmsAgent.getUsethirdapp()==Constant.CONST_YES){
                qrcode = machineQRCodeWechatappPrefix + upmsAgent.getId() +"/" + umbrellaHardwareMachine.getCode();
                logoImgFile = resourcesPath + File.separator + upmsAgent.getId() + ".png";
            }
            ByteArrayOutputStream byteArrayOutputStream = QRCodeUtil.encodeIO(qrcode, logoImgFile, true);
            FileOutputStream fos = new FileOutputStream(imageFile);
            byteArrayOutputStream.writeTo(fos);
            fos.flush();
            fos.close();
            byteArrayOutputStream.close();
        }
        //String imgUrl = request.getContextPath() + "/" + "resources" + "/" + "qrcode" + "/" + umbrellaHardwareMachine.getCode() + "." + QRCodeUtil.FORMAT_NAME;
        //return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, imgUrl);
        InputStream inputStream = new FileInputStream(imageFile);
        byte[] data = new byte[(int)imageFile.length()];
        int length = inputStream.read(data);
        inputStream.close();
        // 清空response
        response.reset();
        // 定义返回参数
        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 下载伞机二维码
     * @param ids
     * @param request
     * @param response
     * @throws Exception
     */
    @ApiOperation(value = "下载伞机二维码")
    @RequiresPermissions("umbrella:machine:downloadqrcode")
    @RequestMapping(value = "/downloadQRCode/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadQRCode(@PathVariable("ids") String ids, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //判断文件夹是否存在
        String realPath = request.getSession().getServletContext().getRealPath("");
        String resourcesPath = (realPath.endsWith(File.separator)?realPath:realPath+File.separator) + "resources";
        String qrcodePath =  resourcesPath+ File.separator + "qrcode";
        File filedir = new File(qrcodePath);
        if (!filedir.exists()) {
            filedir.mkdir();
        }
        String logoImgFile = resourcesPath + File.separator + UmbrellaConstant.QRCODE_LOGO_IMAGE_NAME;
        //解析并查询伞机列表
        List<UmbrellaHardwareMachine> machineList = new ArrayList<UmbrellaHardwareMachine>();
        if(StringUtils.isNotBlank(ids) && !ids.equals("0")){
            String[] idArr = ids.split(",");
            ArrayList<Integer> idList = new ArrayList<Integer>();
            for(int i=0;i<idArr.length;i++){
                idList.add(Integer.parseInt(idArr[i]));
            }
            UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
            machineExample.createCriteria().andIdIn(idList);
            machineList = umbrellaHardwareMachineService.selectByExample(machineExample);
        }else{
            UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
            machineList = umbrellaHardwareMachineService.selectByExample(machineExample);
        }

        String  machineQRCodeWechatappPrefix= upmsSystemParamService.querySystemParamValueByParam_key("QRCODE_MACHINE_WECHATAPP_PREFIX_PROD");
        //组合文件列表
        List<File> files = new ArrayList<File>();
        for(int i=0;i<machineList.size();i++ ){
            String qrcodeImg = qrcodePath + File.separator + machineList.get(i).getCode() + "." + QRCodeUtil.FORMAT_NAME;
            File imageFile = new File(qrcodeImg);
            //判断文件是否存在，则生成
            if (!imageFile.exists()) {
                // 拿到图片流https://www.bjs-tech.cn/api/mqrcode/prod/dev0001
                String qrcode = machineQRCodeWechatappPrefix + UmbrellaConstant.QRCODE_MACHINE_WECHATAPP_PREFIX_PROD + machineList.get(i).getCode();
                logoImgFile = resourcesPath + File.separator + UmbrellaConstant.QRCODE_LOGO_IMAGE_NAME;
                //判断对应代理是否使用独立小程序
                UpmsAgent upmsAgent = upmsAgentService.selectByPrimaryKey(machineList.get(i).getAgentId());
                if(upmsAgent!=null && upmsAgent.getUsethirdapp()==Constant.CONST_YES){
                    qrcode = machineQRCodeWechatappPrefix + upmsAgent.getId() +"/" + machineList.get(i).getCode();
                    logoImgFile = resourcesPath + File.separator + upmsAgent.getId() + ".png";
                }
                ByteArrayOutputStream byteArrayOutputStream = QRCodeUtil.encodeIO(qrcode, logoImgFile, true);
                FileOutputStream fos = new FileOutputStream(imageFile);
                byteArrayOutputStream.writeTo(fos);
                fos.flush();
                fos.close();
                byteArrayOutputStream.close();
            }
            files.add(imageFile);
        }

        // 在服务器端创建打包下载的临时文件
        String randomName = UUID.randomUUID().toString();
        String zipFileName = qrcodePath + File.separator + randomName + ".zip";
        File zipFile = new File(zipFileName);
        // 文件输出流
        FileOutputStream outStream = new FileOutputStream(zipFileName);
        // 压缩流
        ZipOutputStream zipOutputStream = new ZipOutputStream(outStream);
        ZipUtil.zipFile(files, zipOutputStream);
        zipOutputStream.close();
        outStream.close();
        // 以流的形式下载文件。
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFile.getName().getBytes("UTF-8"),"ISO-8859-1"));
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
        //将生成的服务器端文件删除
        zipFile.delete();
    }
    @ApiOperation(value = "将伞机容量余量从伞道同步")
    @RequiresPermissions("umbrella:machine:update")
    @RequestMapping(value = "/synPath/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object synPath(@PathVariable("ids") String ids) {
        if(StringUtils.isBlank(ids)){
            return new UmbrellaResult(UmbrellaResultConstant.FAILED, "未选择伞机");
        }
        String[] idArr = ids.split(",");
        ArrayList<Integer> idList = new ArrayList<Integer>();
        for(int i=0;i<idArr.length;i++){
            idList.add(Integer.parseInt(idArr[i]));
        }
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andIdIn(idList);
        List<UmbrellaHardwareMachine> machineList = umbrellaHardwareMachineService.selectByExample(machineExample);

        if(machineList==null || machineList.isEmpty()){
            return new UmbrellaResult(UmbrellaResultConstant.FAILED, "未选择伞机");
        }
        for(int i=0;i<machineList.size();i++){
            String machineCode = machineList.get(i).getCode();
            UmbrellaHardwarePathExample pathExample = new UmbrellaHardwarePathExample();
            pathExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL).andMachineCodeEqualTo(machineCode);
            List<UmbrellaHardwarePath> pathList = umbrellaHardwarePathService.selectByExample(pathExample);
            int capacity = 0;
            int remainder=0;
            if(pathList!=null && pathList.size()>0){
                for(int j=0;j<pathList.size();j++){
                    capacity = capacity + pathList.get(j).getCapacity();
                    remainder = remainder + pathList.get(j).getRemainder();
                }
            }
            UmbrellaHardwareMachine updateMachine = new UmbrellaHardwareMachine();
            updateMachine.setCapacity(capacity);
            updateMachine.setRemainder(remainder);
            UmbrellaHardwareMachineExample updateExample = new UmbrellaHardwareMachineExample();
            updateExample.createCriteria().andCodeEqualTo(machineCode);
            int count = umbrellaHardwareMachineService.updateByExampleSelective(updateMachine,updateExample);
        }

       return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, "同步完成");
    }


    @ApiOperation(value = "修改伞机代理")
    @RequiresPermissions("umbrella:machine:changeAgent")
    @RequestMapping(value = "/changeAgent/{id}", method = {RequestMethod.GET})
    public String changeAgent(@PathVariable("id") int id, ModelMap modelMap) {

        UpmsAgentExample example = new UpmsAgentExample();
        example.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
        List<UpmsAgent> upmsAgents = upmsApiService.selectUpmsAgentByExample(example);
        modelMap.put("upmsAgents", JsonUtil.object2Json(upmsAgents));

        UmbrellaHardwareMachine umbrellaHardwareMachine = umbrellaHardwareMachineService.selectByPrimaryKey(id);
        modelMap.put("umbrellaHardwareMachine", umbrellaHardwareMachine);
        return "/manage/machine/changeagent.jsp";
    }

    @ApiOperation(value = "修改伞机代理")
    @RequiresPermissions("umbrella:machine:changeAgent")
    @RequestMapping(value = "/changeAgent/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object changeAgent(@PathVariable("id") Integer id, UmbrellaHardwareMachine umbrellaHardwareMachine) {
        umbrellaHardwareMachine.setId(id);
        int count = umbrellaHardwareMachineService.updateByPrimaryKeySelective(umbrellaHardwareMachine);
        try {
            //设置伞道新代理
            UmbrellaHardwarePath umbrellaHardwarePath = new UmbrellaHardwarePath();
            umbrellaHardwarePath.setAgentId(umbrellaHardwareMachine.getAgentId());
            //更新条件
            UmbrellaHardwarePathExample pathExample = new UmbrellaHardwarePathExample();
            pathExample.createCriteria().andMachineCodeEqualTo(umbrellaHardwareMachineService.selectByPrimaryKey(id).getCode());
            umbrellaHardwarePathService.updateByExampleSelective(umbrellaHardwarePath, pathExample);
        } catch (Exception e) {
            LOGGER.error("修改伞机代理时修改伞道异常,id=" + id, e);
        }
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "地图")
    @RequiresPermissions("umbrella:machine:read")
    @RequestMapping(value = "/map", method = {RequestMethod.GET})
    public String map(ModelMap modelMap) {
        return "/manage/machine/map.jsp";
    }
}
